import java.util.ArrayList;
import java.util.Arrays;

public class HeapTest {
    public int[] elem;
    public int usedSize;
    
    public HeapTest(){
        this.elem = new int[10];
    }
    
    public void init(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
    }

    //时间复杂度：O(N)
    public void createHeap(){
        for (int parent = (elem.length - 1 - 1) / 2; parent  >= 0 ; parent--) {
            shiftDown(parent,this.usedSize);
        }
    }

    private void shiftDown(int parent, int usedSize) {
        int child = (parent * 2 + 1);
        while (child < usedSize){
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[child] > elem[parent]){
               swap(elem,parent,child);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

    private void swap(int[] elem,int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,2 * elem.length);
        }

        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0){
            if(elem[child] > elem[parent]){
                swap(elem,parent,child);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    private boolean isFull(){
        return usedSize == elem.length;
    }

    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int val = elem[0];
        usedSize--;
        swap(elem,0,usedSize);
        shiftDown(0,usedSize);
        return val;
    }

    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

}
